package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.CustomException;
import com.itheima.common.R;
import com.itheima.constant.CommonConstant;
import com.itheima.dto.AddDishDto;
import com.itheima.dto.UpdateDishDto;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Flavors;
import com.itheima.mapper.CategoryMapper;
import com.itheima.mapper.DishMapper;
import com.itheima.mapper.FlavorsMapper;
import com.itheima.service.DishService;
import com.itheima.vo.DishVO;
import com.itheima.vo.DishVoPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
 *菜品模块业务层实现类
 * @author msi
 * @date 2022/5/17
 * @version 1.0
 */
@Service
public class DishServiceImpl implements DishService {

    @Resource
    private DishMapper dishMapper;
    @Resource
    private FlavorsMapper flavorsMapper;
    @Resource
    private CategoryMapper categoryMapper;
    // @Resource
    // private RedisTemplate<Object, Object> redisTemplate;
    @Resource
    private CacheManager cacheManager;
    @Override
    public DishVO selectById(String id) {
        Dish dish = dishMapper.selectById(id);
        QueryWrapper<Flavors> qw = new QueryWrapper<>();
        qw.eq("dish_id", id);
        List<Flavors> flavors = flavorsMapper.selectList(qw);
        DishVO dishVO = new DishVO();

        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    @Override
    @CacheEvict(value = "dishCache", allEntries = true)
    public Boolean addDish(AddDishDto addDishDto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(addDishDto, dish);
        String categoryId = dish.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        dish.setType(category.getType());
        int dishInt = dishMapper.insert(dish);

        List<Flavors> flavors1 = addDishDto.getFlavors();

        if (flavors1.size() != 0) {
            for (Flavors flavors : flavors1) {
                flavors.setDishId(dish.getId());
                flavorsMapper.insert(flavors);
            }
        }
        if (dishInt <= 0) {
            throw new CustomException("菜品添加失败");
        }

        // Set<Object> keys = redisTemplate.keys(CommonConstant.DISH_ID + "*");
        // redisTemplate.delete(keys);

        return true;
    }

    @Override
    public DishVoPage getPage(Integer page, Integer pageSize) {
        IPage<Dish> iPage = new Page<>(page, pageSize);
        dishMapper.selectPage(iPage, null);
        List<Dish> records = iPage.getRecords();
        List<DishVO> dishVos = new ArrayList<>();

        for (Dish dish : records) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            Category category = categoryMapper.selectById(dish.getCategoryId());
            dishVO.setCategoryName(category.getName());
            dishVos.add(dishVO);
        }
        for (DishVO dishVO : dishVos) {
            Flavors flavors = flavorsMapper.selectById(dishVO.getId());
            dishVO.setFlavors(flavors);
        }
        DishVoPage dishVoPage = new DishVoPage();

        dishVoPage.setRecords(dishVos);
        dishVoPage.setTotal(iPage.getTotal());
        dishVoPage.setCurrent(page);
        dishVoPage.setSize(pageSize);

        return dishVoPage;
    }

    @Override
    public Boolean deleteById(String ids) {
        int i = 0;
        String[] split = ids.split(",");
        for (String s : split) {
            i = dishMapper.deleteById(s);
        }

        for (String s : split) {
            QueryWrapper<Flavors> qw = new QueryWrapper<>();
            qw.eq("dish_id", s);
            int delete = flavorsMapper.delete(qw);
        }

        return i > 0;
    }

    @Override
    @CacheEvict(value = "dishCache", allEntries = true)
    public Boolean update(UpdateDishDto updateDishDto) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(updateDishDto, dish);
        String categoryId = dish.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        dish.setType(category.getType());
        int dishInt = dishMapper.updateById(dish);

        List<Flavors> flavors1 = updateDishDto.getFlavors();

        if (flavors1.size() != 0) {
            for (Flavors flavors : flavors1) {
                flavors.setDishId(dish.getId());
                QueryWrapper<Flavors> qw = new QueryWrapper<>();
                qw.eq("dish_id",dish.getId());
                flavorsMapper.delete(qw);
                flavorsMapper.insert(flavors);
            }
        }
        // Set<Object> keys = redisTemplate.keys(CommonConstant.DISH_ID + "*");
        // if(Objects.nonNull(keys)){
        //     redisTemplate.delete(keys);
        // }

        return dishInt > 0;
    }

    @Override
    @CacheEvict(value = "dishCache", allEntries = true)
    public Boolean changeStatus(Integer status, String ids) {
        String[] split = ids.split(",");
        int i = 0;
        for (String id : split) {
            Dish dish = dishMapper.selectById(id);
            dish.setStatus(status);
            i = dishMapper.updateById(dish);
        }

        // Set<Object> keys = redisTemplate.keys(CommonConstant.DISH_ID + "*");
        // if(Objects.nonNull(keys)){
        //     redisTemplate.delete(keys);
        // }
        return i > 0;
    }

    @Override
    public List<DishVO> getList(String categoryId) {

        List<DishVO> dishVOList = new ArrayList<>();
        QueryWrapper<Dish> qw = new QueryWrapper<>();
        qw.eq("category_id", categoryId);
        List<Dish> dishes = dishMapper.selectList(qw);

        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            QueryWrapper<Flavors> qwf = new QueryWrapper<>();
            qwf.eq("dish_id", dish.getId());
            List<Flavors> flavors = flavorsMapper.selectList(qwf);
            Category category = categoryMapper.selectById(categoryId);

            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setFlavors(flavors);
            dishVO.setCategoryName(category.getName());
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }

    /**
     * 手机端专用
     *
     * @param categoryId
     * @param status
     * @return
     */
    @Cacheable(value = "dishCache", key = "#categoryId+'_'+#status")
    @Override
    public List<DishVO> getList(String categoryId, Integer status) {
        String key = CommonConstant.DISH_ID + categoryId + "_" + status;

        // List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        // if (dishVOList != null) {
        //     return dishVOList;
        // }
        List<DishVO>  dishVOList = new ArrayList<>();

        QueryWrapper<Dish> qw = new QueryWrapper<>();
        qw.eq("category_id", categoryId);
        qw.eq("status", status);
        List<Dish> dishes = dishMapper.selectList(qw);

        for (Dish dish : dishes) {
            DishVO dishVO = new DishVO();
            QueryWrapper<Flavors> qwf = new QueryWrapper<>();
            qwf.eq("dish_id", dish.getId());
            List<Flavors> flavors = flavorsMapper.selectList(qwf);
            Category category = categoryMapper.selectById(categoryId);

            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setFlavors(flavors);
            dishVO.setCategoryName(category.getName());
            dishVOList.add(dishVO);
        }

        // redisTemplate.opsForValue().set(key, dishVOList, 60, TimeUnit.MINUTES);

        return dishVOList;
    }
}
